<template>
  <div class="email-search-box">
    <el-select
      class="select-search-box"
      v-model="value"
      multiple
      filterable
      remote
      :size="size"
      default-first-option
      allow-create
      @change="changeFun"
      @remove-tag="removeTagFun"
      :remote-method="remoteMethod"
      :loading="loading"
      :placeholder="placeholder">
      <el-option
        v-for="(item, index) in options"
        :key="index"
        :label="item.label"
        :value="item.value"
        :disabled="item.disabled">
      </el-option>
    </el-select>
  </div>
</template>

<script>
  import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'emailSearch',
    data () {
      return {
        value: [],
        list: [],
        loading: false,
        options: [],
        states: [],
        outThrowValue: [],
        outThrowValueObj: []
      }
    },
    created () {
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        let data
        data = deepClone(agents)
        data.map((item, index) => { // 找出系统座席中未绑定邮箱
          if (item.email === '') {
            item.email = '邮箱未绑定'
          }
          this.states.push({name: item.displayName + ' (' + item.email + ')', flag: '&' + item.email})
        })
        if (this.dataArray.length) {
          let association = deepClone(this.dataArray)
          let arrNew = []
          association.map(item => {
            arrNew.push({name: item.recipent + ' (' + item.recipent + ')', flag: '&' + item.recipent})
          })
          let cons = deepClone(this.states)
          arrNew.push(...cons)
          this.states = deepClone(arrNew)
        }
        this.list = this.states.map(item => {
          if (item.name.indexOf('邮箱未绑定') > -1) {
            return {value: item.flag, label: item.name.substring(0, 100), disabled: true}
          } else {
            return {value: item.flag, label: item.name.substring(0, 100), disabled: false}
          }
        })
        this.initData()
      })
    },
    props: {
      size: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: ''
      },
      dataArray: {
        default: function () {
          return []
        }
      },
      inputData: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    watch: {
      value: {
        handler (curVal, oldVal) {
//          this.oldVal = oldVal
        }
      },
      inputData () {
        this.initData()
      }
    },
    methods: {
      remoteMethod (query) { // 智能联想处理
        if (query !== '') {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            this.options = this.list.filter(item => {
              return item.label.toLowerCase()
                .indexOf(query.toLowerCase()) > -1
            })
          }, 200)
        } else {
          this.options = []
        }
      },
      changeFun (val) { // 值被选中的处理
        let self = this
        let reg = new RegExp(/^[a-z0-9A-Z]+([._\\-]*[a-z0-9A-Z])*@([a-z0-9A-Z]+[-a-z0-9A-Z]*[a-z0-9A-Z]+.){1,63}[a-z0-9A-Z]+$/)
        if (!reg.test(val[val.length - 1])) { // 验证没通过
          let selectedValue = this.list.filter(item => {
            return item.value.indexOf(val[val.length - 1]) > -1 && item.disabled === false
          })
          if (selectedValue.length > 0) { // 不是手输的
            val[val.length - 1] = selectedValue[0].label.split('').reverse().join('').split('( ')[1].split('').reverse().join('')
            let countNum = 0
            this.value.map(item => {
              if (item === val[val.length - 1]) { // 判断邮箱是否被选中
                countNum += 1
              }
            })
            if (countNum > 1) { // 判断邮箱是否被选中
              this.value.pop()
              this.$message.error('邮箱已被选中')
            }
          } else {
            let newValue = this.list.find(item => {
              return item.label.split(' (')[0] === val[val.length - 1]
            })
            if (typeof newValue !== 'object' && this.value.length > 0) { // 判断邮箱格式是否正确
              this.value.pop()
              this.$message.error('邮箱格式不正确')
            }
          }
        }
        this.outThrowValue = deepClone(self.value)
        this.outThrowValue.map((item, index) => { // 外抛值处理
//          防止名称包含情况的出现  例如：张京&&张京京
          let newValue = null
          for (let i = 0; i < self.list.length; i++) {
            const labelArr = self.list[i].label.split('').reverse().join('').split('( ')
            let labelNew = ''
            if (labelArr && labelArr[1]) {
              labelNew = labelArr[1].split('').reverse().join('')
            }
            if (labelNew === item) {
              newValue = self.list[i]
              break
            }
          }
//          let newValue = self.list.find(listItem => {
//            return listItem.label.indexOf(item) > -1
//          })
          if (newValue) { // 系统中的座席
            self.outThrowValue.splice(index, 1, {name: newValue.label.split(' (')[0], addr: newValue.label.split(' (')[1].split(')')[0]})
          } else {
            let lastValue = self.outThrowValue[index]
            let name = lastValue.split('@')[0]
            let addr = lastValue
            self.outThrowValue.splice(index, 1, {name: name, addr: addr})
          }
        })
        this.$nextTick(function () {
          this.$emit('inputChange', self.outThrowValue)
        })
      },
      initData () { // 初始回显值
        this.value = []
        let self = this
        self.inputData.forEach((item, index) => {
          let newValue = self.list.filter((listItem) => listItem.label.indexOf(item.addr) > -1)[0]
          if (newValue) {
            self.value.push(newValue.label.split(' (')[0])
          } else {
            self.value.push(item.addr)
          }
          this.$nextTick(function () {
            this.$emit('initData')
          })
        })
      },
      removeTagFun (val) {
        this.outThrowValueObj.pop()
      }
    }
  }
</script>

<style lang="stylus">
  .email-search-box
    .select-search-box
      width 100%
    .el-input__inner
      cursor text !important
      border-color #999 !important
    .el-select .el-tag
      background-color #e0eeff
    .el-select__tags
      max-width 100%
      span
        max-width 100%
        .el-tag el-tag--info el-tag--mini
          max-width calc(100% - 20px)
      .el-tag__close.el-icon-close
        top 3px
        right 2px
        position absolute
      .el-select__tags-text
        max-width: 100%
        text-overflow: ellipsis
        overflow: hidden
        display: inline-block
      .el-tag--info
        max-width 100%
        position relative
        padding 0 20px 0 4px
</style>
